import React, { useState, useRef, useEffect } from 'react';
import './index.css';
import { useDrag, useDrop, DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import DraggableItem from './DraggableItem';

const ITEM_TYPE = 'sider-item';
const SiderItem = ({ name, id }) => {
    const [, drag] = useDrag(() => ({
        type: ITEM_TYPE,
        item: { name, id },
        collect: (monitor) => ({
            isDragging: monitor.isDragging(),
        }),
    }));
    return <div ref={drag} className="sider-item" key={id} style={{ cursor: 'pointer', padding: '10px', border: '1px solid gray', margin: '5px', transition: 'all 0.3s ease' }}>{name}</div>;
}
const MainItem = ({ itemKey, droppedItems, onDrop, children }) => {
    const droppedItemsRef = useRef(droppedItems);
    droppedItemsRef.current = droppedItems;
    const [, drop] = useDrop(() => ({
        accept: ITEM_TYPE,
        drop: (item, monitor) => {
            // 是否已存在相同元素
            const itemExists = droppedItemsRef.current.some(droppedItem => droppedItem.id === item.id);
            if (!itemExists) {
                onDrop(item, itemKey, 'add');
            }
            console.log(droppedItemsRef.current, "==MainItem== droppedItemsRef.current.====");
            console.log(droppedItems, "==MainItem== droppedItems====");
            console.log(itemKey, "==MainItem== itemKey====");
            console.log(children, "==MainItem== children====");
            console.log(monitor, "==MainItem== monitor====");
            return item;
        },
        collect: (monitor) => ({
            isOver: monitor.isOver(),
            canDrop: monitor.canDrop(),
        }),
    }));

    const changeDropHover = (dragIndex, hoverIndex, itemKey) => {
        console.log(dragIndex, "====dragIndex====");
        console.log(hoverIndex, "====hoverIndex====");
        console.log(itemKey, "====itemKey====");
        console.log(droppedItemsRef.current, "====droppedItemsRef.current====");


        if (dragIndex !== hoverIndex) {
            let newItems = [...droppedItemsRef.current];

            const draggedItem = newItems.splice(dragIndex, 1)[0];

            newItems.splice(hoverIndex, 0, draggedItem);
            console.log(newItems, "===newItems=====");
            onDrop(newItems, itemKey, 'setAll');

        }




        // const index = droppedItemsRef.current.findIndex(
        //   (item) => item.id === draggedItemId
        // );
        // const itemToMove = droppedItemsRef.current[index];

        // // Remove the dragged item and add it to the new position
        // const newItems = droppedItemsRef.current.filter(
        //   (item) => item.id !== draggedItemId
        // );
        // newItems.splice(targetIndex, 0, itemToMove);

    }



    return (

        <div ref={drop} className={`main-item ${itemKey}`} >
            {children}
            <DraggableItem droppedItems={droppedItems} itemKey={itemKey} changeDropHover={changeDropHover}></DraggableItem>
            {/* {droppedItems.map((droppedItem, index) => (
                <span key={index} style={{ padding: '5px', border: '1px solid gray', margin: '5px', borderRadius: '5px', transition: 'all 0.3s ease' }}>{droppedItem.name}</span>
            ))} */}
        </div>
    );
}

const index = () => {

    const [droppedItemsRow, setDroppedItemsRow] = useState([]);
    const [droppedItemsCol, setDroppedItemsCol] = useState([]);
    const [data, setData] = useState([
        {
            name: '小倩',
            id: '1',
        },
        {
            name: '小明',
            id: '2',
        },
        {
            name: '小红',
            id: '3',
        },
        {
            name: '小李',
            id: '4',
        }
    ]);

    const handleDropRowClo = (item, type, opType) => {



        let menuMap = {
            coladd: () => {
                if (!droppedItemsCol.some(droppedItem => droppedItem.id === item.id)) {
                    setDroppedItemsCol(prevItems => [...prevItems, item]);
                }
            },
            colsetAll: () => {
                setDroppedItemsCol(() => [...item]);
            },
            rowadd: () => {
                if (!droppedItemsRow.some(droppedItem => droppedItem.id === item.id)) {
                    setDroppedItemsRow(prevItems => [...prevItems, item]);
                }
            },
            rowsetAll: () => {
                setDroppedItemsRow(() => [...item])
            },
        }
        menuMap[type + opType]()

        console.log(item, "=====handleDropCol=======item============");
        console.log(droppedItemsCol, "=====handleDropCol=======handleDropCol============");
        console.log(droppedItemsRow, "=====handleDropCol=======droppedItemsRow============");
    };

    useEffect(() => {

        console.log(droppedItemsRow, "=====useEffect=======droppedItemsRow============");

    }, [droppedItemsRow])

    useEffect(() => {

        console.log(droppedItemsCol, "=====useEffect=======droppedItemsCol============");

    }, [droppedItemsCol])


    return (
        <DndProvider backend={HTML5Backend}>
            <div className="lsftRightSort" style={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>
                <div style={{ backgroundColor: 'lightgray', padding: '10px', textAlign: 'center' }}>top</div>
                <div className="main-content" >
                    <div className="sider">
                        {data.map((v) => (
                            <SiderItem key={v.id} name={v.name} id={v.id} />
                        ))}
                    </div>
                    <div className="main">
                        <div className='main-box' >
                            <MainItem
                                itemKey='row'
                                droppedItems={droppedItemsRow}
                                onDrop={handleDropRowClo}
                            >
                                <span>行</span>
                            </MainItem>
                            <MainItem
                                itemKey='col'
                                droppedItems={droppedItemsCol}
                                onDrop={handleDropRowClo}
                            >
                                <span>列</span>
                            </MainItem>
                        </div>
                    </div>
                </div>
            </div>
        </DndProvider>
    );
}

export default index;